package org.adream.account.service.async;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.adream.account.dao.Dream2020CertificationDao;
import org.adream.account.dao.Dream2020RoleUserLinkDao;
import org.adream.account.dao.Dream2020SchoolBlogDao;
import org.adream.account.dao.Dream2020SchoolDao;
import org.adream.account.dao.Dream2020UserDao;
import org.adream.account.entity.Dream2020CertificationEntity;
import org.adream.account.entity.Dream2020SchoolEntity;
import org.adream.account.entity.Dream2020UserEntity;
import org.adream.account.model.SynDream2020DataModel;
import org.adream.account.util.Constant;
import org.adream.account.util.DataSourceContextHolder;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

/**
 * 同步新版盒子数据service
 * @author sl
 *
 */
@Component
@EnableAsync
public class SynDream2020Service {
	
	@Autowired
	private Dream2020SchoolDao dream2020SchoolDao;
	
	@Autowired
	private Dream2020UserDao dream2020UserDao;
	
	@Autowired
	private Dream2020CertificationDao dream2020CertificationDao;
	
	@Autowired
	private Dream2020RoleUserLinkDao dream2020RoleUserLinkDao;
	
	@Autowired
	private Dream2020SchoolBlogDao dream2020SchoolBlogDao;
	
	@Resource
	private TaskExecutor taskExecutor;
	
	private final static Logger logger = LoggerFactory.getLogger(SynDream2020Service.class);
	
	/**
	 * 同步新版盒子数据
	 * @return
	 */
	@Async
	public void synDream2020Data(SynDream2020DataModel data) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				//切换数据源
				DataSourceContextHolder.setDbType(Constant.ADREAM_BOX_2020_DATA_SOURCE_NAME);
				//通过casid匹配
				Dream2020UserEntity dream2020User = dream2020UserDao.queryDream2020UserByCasId(data.getCasid());
				if(dream2020User == null) {
					if(data.getIsTeacher() != null && data.getIsTeacher()) {
						//通过手机号匹配
						dream2020User = dream2020UserDao.queryDream2020UserByPhone(data.getPhone());
						if(dream2020User != null) {
							dream2020User.setCasid(data.getCasid());
							dream2020UserDao.bindDream2020UserCasId(dream2020User);
						} else {
							//通过邮箱匹配
							dream2020User = Utils.isEmptyCollection(dream2020UserDao.queryDream2020UsersByEmail(data.getEmail())) ? null 
									: dream2020UserDao.queryDream2020UsersByEmail(data.getEmail()).get(0);
							if(dream2020User != null) {
								dream2020User.setCasid(data.getCasid());
								dream2020UserDao.bindDream2020UserCasId(dream2020User);
							} else {
								//创建新用户
								dream2020User = new Dream2020UserEntity();
								dream2020User.setCasid(data.getCasid());
								dream2020User.setName(data.getName());
								dream2020User.setEmail(data.getEmail());
								dream2020User.setPhone(data.getPhone());
								dream2020User.setPassword("RegByCas");
								dream2020User.setSex(data.getSex());
								dream2020User.setCreatedAt(new Date());
								dream2020User.setUpdatedAt(new Date());
								int addDream2020UserResult = dream2020UserDao.addDream2020User(dream2020User);
								if(addDream2020UserResult == Constant.ZERO) {
									logger.warn("同步更新新版盒子-新增盒子用户数据出错,数据库错误:(");
									return;
								}
							}
						}
					} else {
						logger.warn("根据casid查询用户,用户不存在:(");
						return;
					}
				}
				Utils.copyPropertiesIgnoreNull(data, dream2020User);
				dream2020User.setUpdatedAt(new Date());
				int updateDream2020UserResult = dream2020UserDao.updateDream2020User(dream2020User);
				if(updateDream2020UserResult == Constant.ZERO) {
					logger.warn("同步更新新版盒子数据出错,数据库错误:(");
					return;
				}
				
				int id = dream2020User.getId();
				//更新过'实名认证'
				if(data.getVerified() != null) {
					//已实名 添加'实名'角色
					if(Constant.VERIFIED.equals(data.getVerified())) {
						dream2020RoleUserLinkDao.replaceDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_REALNAME_ROLE_ID);
					} else {
						dream2020RoleUserLinkDao.deleteDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_REALNAME_ROLE_ID);
					}
				}
				if(!StringUtils.isEmpty(data.getSchoolNumber())) {					
					//直接取第一个,避免数据错误
					Dream2020SchoolEntity dream2020School = dream2020SchoolDao.queryDream2020SchoolsBySchoolNumber(data.getSchoolNumber()).get(0);
					//更新过'梦想教师认证'
					if(data.getIsTeacher() != null) {
						Dream2020CertificationEntity dream2020Certification = dream2020CertificationDao.queryDream2020Certification(id, Constant.DREAM_2020_CERTIFICATION_NAME_TEACHER_OR_DREAM_ADMIN, Constant.DREAM_2020_USER_GROUP_TEACHER_ROLE_ID);
						if(StringUtils.isEmpty(data.getSchoolNumber()) || Utils.isEmptyCollection(dream2020SchoolDao.queryDream2020SchoolsBySchoolNumber(data.getSchoolNumber()))) {
							logger.warn("更新用户梦想教师失败,school_number:" + data.getSchoolNumber() + "未对应相应学校:(");
							return;
						}
						//梦想教师已通过
						if(data.getIsTeacher()) {
							//添加  梦想教师角色
							dream2020RoleUserLinkDao.replaceDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_TEACHER_ROLE_ID);
							if(dream2020Certification != null) {
								dream2020Certification.setSid(dream2020School.getId());
								dream2020Certification.setStatus(Constant.ONE);
								dream2020CertificationDao.checkDream2020Certification(dream2020Certification);
							} else {
								if(Utils.isEmptyCollection(dream2020SchoolDao.queryDream2020SchoolsBySchoolNumber(data.getSchoolNumber()))) {
									logger.warn("同步新版盒子数据失败,sid为空:(");
									return;
								} else if(dream2020SchoolDao.queryDream2020SchoolsBySchoolNumber(data.getSchoolNumber()).size() > Constant.ONE) {
									logger.warn("school_number:" + data.getSchoolNumber() + "存在多条学校记录");
									return;
								}
								dream2020Certification = new Dream2020CertificationEntity();
								dream2020Certification.setCertificationName(Constant.DREAM_2020_CERTIFICATION_NAME_TEACHER_OR_DREAM_ADMIN);
								dream2020Certification.setUserId(id);
								dream2020Certification.setSid(dream2020School.getId());
								JSONObject jsonObject = new JSONObject();
								jsonObject.put("name", dream2020User.getName() == null ? "" : dream2020User.getName());
								jsonObject.put("phone", dream2020User.getPhone() == null ? "" : dream2020User.getPhone());
								jsonObject.put("realname", data.getRealname());
								jsonObject.put("desc", "梦想教师账号");
								dream2020Certification.setData(jsonObject.toJSONString());
								dream2020Certification.setExaminer(id);
								dream2020Certification.setStatus(Constant.ONE);
								dream2020Certification.setCreatedAt(new Date());
								dream2020Certification.setUpdatedAt(new Date());
								dream2020Certification.setType(Constant.ZERO);
								dream2020Certification.setLevel(Constant.ZERO);
								dream2020Certification.setRolesId(Constant.DREAM_2020_USER_GROUP_TEACHER_ROLE_ID);
								int addDream2020CertificationResult = dream2020CertificationDao.addDream2020Certification(dream2020Certification);
								if(addDream2020CertificationResult == Constant.ZERO) {
									logger.warn("同步更新新版盒子数据出错,数据库错误:(");
									return;
								}
							}
							//更新用户的动态同步到新认证的学校
							dream2020SchoolBlogDao.updateSidByUidAndCreateTime(dream2020School.getId(), id, data.getCreateTime());
						} else {
							//去除 梦想教师角色
							dream2020RoleUserLinkDao.deleteDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_TEACHER_ROLE_ID);
							//查询 认证,认证存在,审核失败
							if(dream2020Certification != null) {
								dream2020Certification.setSid(dream2020School.getId());
								dream2020Certification.setStatus(Constant.TWO);
								dream2020CertificationDao.checkDream2020Certification(dream2020Certification);
							}
						}
					}
					//更新过'梦想中心主任'角色
					if(data.getIsDreamDirector() != null) {
						//判断是否是'梦想中心主任'
						if(data.getIsDreamDirector()) {
							//需要去除之前该学校的'梦想中心主任'角色用户
							List<Dream2020UserEntity> directors = dream2020UserDao.queryDirectorsBySchoolNumberAndTypeAndRleId(data.getSchoolNumber(), Constant.ZERO, Constant.DREAM_2020_USER_GROUP_DREAM_ADMIN_ROLE_ID);
							if(!Utils.isEmptyCollection(directors)) {
								directors.forEach(d -> {
									dream2020RoleUserLinkDao.deleteDream2020RoleUser(d.getId(), Constant.DREAM_2020_USER_GROUP_DREAM_ADMIN_ROLE_ID);
								});
							}
							//添加 梦想中心主任角色
							dream2020RoleUserLinkDao.replaceDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_DREAM_ADMIN_ROLE_ID);
							//更新学校梦想中心主任
							dream2020School.setDreamDirectorUid(id);
							dream2020SchoolDao.updateDreamDirctor(dream2020School);
						} else {
							//去除 梦想中心主任角色
							dream2020RoleUserLinkDao.deleteDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_DREAM_ADMIN_ROLE_ID);
							//更新学校梦想中心主任
							dream2020School.setDreamDirectorUid(0);
							dream2020SchoolDao.updateDreamDirctor(dream2020School);
						}
					}
				}
				//更新过'梦想盒子管理员'角色
				if(data.getIsAdreamboxAdmin() != null) {
					if(data.getIsAdreamboxAdmin()) {
						dream2020RoleUserLinkDao.replaceDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_FOUNDER_ROLE_ID);
					} else {
						dream2020RoleUserLinkDao.deleteDream2020RoleUser(id, Constant.DREAM_2020_USER_GROUP_FOUNDER_ROLE_ID);
					}
				}
				//更新过'星级'角色
				if(data.getRoleIsDelMap() != null && data.getRoleIsDelMap().size() > 0) {
					Map<Integer, Integer> roleIsDelMap = data.getRoleIsDelMap();
					roleIsDelMap.forEach((rleId, isDel) -> {
						if(isDel == 0) {
							dream2020RoleUserLinkDao.replaceDream2020RoleUser(id, rleId);
						} else {
							dream2020RoleUserLinkDao.deleteDream2020RoleUser(id, rleId);
						}
					});
				}
				//清除数据源
				DataSourceContextHolder.clearDbType();
			}
		});
	}
}